package com.yuhanginfo.modules.web.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.yuhanginfo.modules.web.util.WebUserUtils;
import com.yuhanginfo.modules.web.entity.WebAddress;
import com.yuhanginfo.modules.web.entity.WebArea;
import com.yuhanginfo.modules.web.entity.WebYongUser;
import com.yuhanginfo.modules.web.service.AddressService;
import com.yuhanginfo.modules.web.service.WebAreaService;
/**
 * 收货地址管理
 *
 */
@Controller
@RequestMapping(value = "${frontPath}/address")
public class AddressController {
	
	@Autowired
	private AddressService addressService;
	
	@Autowired
	private WebAreaService webAreaService;
	
	@RequestMapping(value = "getAddress")
	@ResponseBody
	public WebAddress getAddress(WebAddress address) {
		return addressService.get(address);
	}
	
	@RequestMapping(value = "selectByUserId")
	@ResponseBody
	public List<WebAddress> selectByUserId() {
		WebYongUser yong = WebUserUtils.getYongUser();
		return addressService.selectByUserId(Integer.parseInt(yong.getId()));
	}
	
	@RequestMapping(value = "saveAddress")
	@ResponseBody
	public WebAddress saveAddress(WebAddress address) {
		WebYongUser yong = WebUserUtils.getYongUser();
		address.setUserId(Integer.parseInt(yong.getId()));
		//如果保存的地址勾选了默认，则去除之前默认的地址
		if("1".equals(address.getIsDef())){
			WebAddress defAddress = addressService.getDefAddress(address);
			if(defAddress!=null){
				defAddress.setIsDef("0");
				addressService.save(defAddress);
			}
		}
		address.setDelFlag("0");
		addressService.save(address);
		return address;
	}
	
	@RequestMapping(value = "save")
	@ResponseBody
	public WebAddress save(WebAddress address) {
		WebYongUser yong = WebUserUtils.getYongUser();
		address.setUserId(Integer.parseInt(yong.getId()));
		//如果保存的地址勾选了默认，则去除之前默认的地址
		if("1".equals(address.getIsDef())){
			WebAddress defAddress = addressService.getDefAddress(address);
			if(defAddress!=null){
				defAddress.setIsDef("0");
				addressService.save(defAddress);
			}
		}
		address.setDelFlag("0");
		addressService.save(address);
		return address;
	}
	
	@RequestMapping(value = "getDefAddress")
	@ResponseBody
	public WebAddress getDefAddress(WebAddress address) {
		WebYongUser yong = WebUserUtils.getYongUser();
		address.setUserId(Integer.parseInt(yong.getId()));
		return addressService.getDefAddress(address);
	}
	
	@RequestMapping(value = "getProvince")
	@ResponseBody
	public List<WebArea> getProvince() {
		return webAreaService.getProvince();
	}
	
	@RequestMapping(value = "selectByParent")
	@ResponseBody
	public List<WebArea> selectByParent(WebArea webArea) {
		return webAreaService.selectByParent(webArea.getId());
	}
}
